<script setup lang="ts">
defineOptions({
  name: "spcCharts"
});
import { ref, onMounted, computed, nextTick } from "vue";
import echartsCom from "@/views/common/components/echartsCom/index.vue";
import cardTitle from "@/views/machine/components/cardTitle/index.vue";
import type { LabelLayoutFunctionType } from "@/views/common/components/types";
import { spcIndicatorqueryResultCount } from "@/api/spc";

interface Props {
  /**  获取当前echarts实例对象，参数为实例对象和回调函数 */
  // getEchartsInstance?: EchartsInstanceType | null;
  /**  获取 optiins 配置函数 */
  labelLayoutFn?: LabelLayoutFunctionType | null;
  /**  同 echarts option */
  // options?: CommonEcharts.CommonEchartsOption | null;
  optionData?: any;
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  title 栏右侧文字 */
  rightText?: string | number;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  color?: string;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  className?: string;
  dateRange?: any;
}

const props = withDefaults(defineProps<Props>(), {
  width: 600,
  height: 400,
  boxShadow: false,
  borderRidus: true
});

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const echartsKey = ref<string>(Math.random().toString(36).slice(2, 10));
const echartsComRef = ref<InstanceType<typeof echartsCom> | null>(null);

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const options = computed(() => {
  const yAxis = [
    {
      type: "value",
      name: props.optionData.indicatorName,
      nameLocation: "middle", //居中
      nameGap: 70, //轴线距离
      nameRotate: 90, //字体选择角度
      axisLine: {
        show: true,
        lineStyle: {
          type: "solid"
        }
      }
    }
  ];
  const series = [
    {
      // data: [400, 400, 400, 400, 400, 400],
      data: props.optionData.pointValues.length > 0 ? props.optionData.pointValues.map(item => item.value) : [],
      type: "line",
      name: props.optionData.indicatorName,
      // areaStyle: {
      //   opacity: 0.15
      // },
      symbol: "none",
      markLine: {
        symbol: "none",
        data: [
          {
            name: "USL值",
            yAxis: Number(props.optionData.uslValue),
            lineStyle: {
              color: "#A600FF",
              wideh: "1",
              type: "solide"
            },
            label: {
              position: "insideEndTop",
              formatter: `USL值${props.optionData.uslValue}`,
              color: "#A600FF",
              fontWeight: 600
            }
          },
          {
            name: "UCL值",
            yAxis: Number(props.optionData.uclValue),
            lineStyle: {
              color: "#FF0000",
              wideh: "1",
              type: "dashed"
            },
            label: {
              position: "insideEndTop",
              formatter: `UCL值${props.optionData.uclValue}`,
              color: "#FF0000",
              fontWeight: 600
            }
          },
          {
            name: "UWL值",
            yAxis: Number(props.optionData.uwlValue),
            lineStyle: {
              color: "#FF9900",
              wideh: "1",
              type: "dashed"
            },
            label: {
              position: "insideEndTop",
              formatter: `UWL值${props.optionData.uwlValue}`,
              color: "#FF9900",
              fontWeight: 600
            }
          },
          {
            name: "Target值",
            yAxis: Number(props.optionData.targetValue),
            lineStyle: {
              color: "#00E272",
              wideh: "1",
              type: "solide"
            },
            label: {
              position: "insideEndTop",
              formatter: `Target值${props.optionData.targetValue}`,
              color: "#00E272",
              fontWeight: 600
            }
          },
          {
            name: "LWL值",
            yAxis: Number(props.optionData.lwlValue),
            lineStyle: {
              color: "#FF9900",
              wideh: "1",
              type: "dashed"
            },
            label: {
              position: "insideEndTop",
              formatter: `LWL值${props.optionData.lwlValue}`,
              color: "#FF9900",
              fontWeight: 600
            }
          },
          {
            name: "LCL值",
            yAxis: Number(props.optionData.lclValue),
            lineStyle: {
              color: "#FF0000",
              wideh: "1",
              type: "dashed"
            },
            label: {
              position: "insideEndTop",
              formatter: `LCL值${props.optionData.lclValue}`,
              color: "#FF0000",
              fontWeight: 600
            }
          },
          {
            name: "LSL值",
            yAxis: Number(props.optionData.lslValue),
            lineStyle: {
              color: "#A600FF",
              wideh: "1",
              type: "solide"
            },
            label: {
              position: "insideEndTop",
              formatter: `LSL值${props.optionData.lslValue}`,
              color: "#A600FF",
              fontWeight: 600
            }
          }
        ]
      }
    }
  ];
  const option = {
    color: [props.color],
    grid: {
      left: "60px",
      top: "40px",
      right: "100px",
      bottom: "10px",
      containLabel: true
    },
    legend: {},
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        props.optionData.pointValues.length > 0
          ? props.optionData.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  return option;
});

const clickHandler = () => emits("btn-click");

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};
const updateEchartsKey = () => {
  echartsKey.value = Math.random().toString(36).slice(2, 10);
};

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const getEcharts = async () => {
  await nextTick();
  return echartsComRef.value.getEcharts();
};

const totalOosCount = ref<any>("");
const totalOocCount = ref<any>("");
const totalOowCount = ref<any>("");

onMounted(async () => {
  updateEchartsKey();
  const oocData: any = await spcIndicatorqueryResultCount({
    jobIdList: [props.optionData.jobId],
    startTime: props.optionData.startTime,
    endTime: props.optionData.endTime
  });
  if (oocData != null) {
    totalOocCount.value = oocData.totalOocCount;
    totalOosCount.value = oocData.totalOosCount;
    totalOowCount.value = oocData.totalOowCount;
  } else {
    totalOocCount.value = 0;
    totalOosCount.value = 0;
    totalOowCount.value = 0;
  }
});

defineExpose({
  getEcharts
});
</script>

<template>
  <div class="echarts-chart" :class="{ boxShadow, borderRidus }">
    <cardTitle v-if="title" :title="title">
      <div class="model-title-slot">
        <span class="right-text">{{ `OOS: ${totalOosCount} OOC: ${totalOocCount} OOW: ${totalOowCount}` }}</span>
        <px-button v-if="button" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
      </div>
    </cardTitle>
    <div class="echarts-chart-com">
      <echartsCom ref="echartsComRef" :key="echartsKey" :labelLayoutFn="labelLayoutFn" :options="options" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.echarts-chart {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
  width: 100%;
  min-width: v-bind(min_width);
  height: 100%;
  min-height: v-bind(min_height);
  // padding: 16px;
  background-color: #fff;
  border: 1px solid #dcdcdc;

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      margin-right: 16px;
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }
  }

  .echarts-chart-com {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: calc(100% - v-bind(title_height));
  }
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}
</style>
